package cn.kgm.base.producer;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

/**
 * 发送异步消息
 */
public class ASyncProducer {

    public static void main(String[] args) throws Exception {
        // step1 创建消息生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("group1" );
        // step2 制定nameserver地址
        producer.setNamesrvAddr("192.168.101.9:9876" );
        // step3 启动producer
        producer.start();
        for (int i = 0; i < 10; i++) {
            // step4 创建消息对象
            Message msg = new Message();
            /*
                参数一，消息主题（类别）
                参数二，消息tag
                参数三，消息内容
             */
            msg.setTopic("kagim-topic-v1" );
            msg.setTags("kagim-topic-v1-tag2-async" );
            msg.setBody(("hello world" + i).getBytes());
            msg.setWaitStoreMsgOK(false);
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(JSON.toJSONString(sendResult));
                }

                @SneakyThrows
                @Override
                public void onException(Throwable throwable) {
                    System.out.println("发送异步消息失败===>" + JSON.toJSONString(throwable));
                }
            });
        }
        producer.shutdown();
    }
}
